package com.peanut.service.impl;

import com.orm.mapper.BaseService;
import com.peanut.entity.*;
import com.peanut.entity.dto.PermissionVO;
import com.peanut.entity.vo.ApiUrlTreeVo;
import com.peanut.mapper.*;
import com.peanut.service.RoleService;
import com.spring.annotation.Autowired;
import com.spring.annotation.Service;
import com.spring.annotation.Transaction;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl extends BaseService<RoleMapper, Role> implements RoleService {
	@Autowired
	private AdminUserMapper adminUserMapper;
	
	@Autowired
	private RoleInterfaceMapper roleInterfaceMapper;
	
	@Autowired
	private RoleMenuMapper roleMenuMapper;
	
	@Autowired
	private ApiUrlMapper apiUrlMapper;
	
	
	@Override
	@Transaction
	public JsonResult deleteRole(int roleId) {
		// 先查下有没有相关用户
		if (adminUserMapper.queryCountByRoleId(roleId)>0) {
			return JsonResult.fail("角色存在关联管理员");
		}
		
		// 就可以直接删除了
		baseMapper.deleteById(roleId);   // 角色表删除   ，应该走个事务，万一删了一半出错怎么搞
		roleMenuMapper.deleteByRoleId(roleId);
		roleInterfaceMapper.deleteByRoleId(roleId);
		
		return JsonResult.success("角色成功删除");
		
	}
	
	
	/**
	 * 查相关 roleId 对应的所有菜单和接口
	 */
	@Override
	public PermissionVO queryPermission(int roleId) {
		PermissionVO permissionVO = new PermissionVO();
		permissionVO.setRoleId(roleId);
		permissionVO.setRoleMenus( roleMenuMapper.queryByRoleId(roleId));
		permissionVO.setRoleInterfaces( roleInterfaceMapper.queryApiUrlIdByRoleId(roleId));
		
		return permissionVO;
	}
	
	
	/**
	 * 更新所有权限 ，事务？？？？？？
	 */
	@Override
	@Transaction
	public boolean updatePermission(PermissionVO permissionVO,Map<Integer, List<String>> permissionsList) {
		Integer roleId = permissionVO.getRoleId();
		
		// 先清空旧权限
		roleMenuMapper.deleteByRoleId(roleId);
		roleInterfaceMapper.deleteByRoleId(roleId);
		
		
		// 写入新权限
		for (Integer menu_id : permissionVO.getRoleMenus()) {
			RoleMenu rm = new RoleMenu();
			rm.setRoleId(roleId);
			rm.setMenuId(menu_id);
			roleMenuMapper.insert(rm);
		}
		for (Integer interfaceUrlId : permissionVO.getRoleInterfaces()) {
			RoleApi ri = new RoleApi();
			ri.setRoleId(roleId);
			ri.setApiUrlId(interfaceUrlId);
			roleInterfaceMapper.insert(ri);
		}
		
		List<String> permissions = roleInterfaceMapper.queryApiUrlByRoleId(roleId);
		permissionsList.put(roleId,permissions);      // 全局域更新权限
		
		return true;
	}
	
	
	@Override
	public List<ApiUrlTreeVo> queryAllInterface() {
		List<ApiUrlTreeVo> apiUrlTreeVos = apiUrlMapper.queryTopApiUri();
		List<ApiUrl> sonApiUrls = apiUrlMapper.querySonApiUri();
		
		for (ApiUrlTreeVo apiUrlTreeVo : apiUrlTreeVos) {
			apiUrlTreeVo.setChildren( sonApiUrls.stream().filter( e-> e.getParentId().equals(apiUrlTreeVo.getId())).collect(Collectors.toList()));
		}
		return apiUrlTreeVos;
	}
}
